package com.tn.wservice.validator;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.util.StringUtils;

import com.tn.wservice.validator.IValidationResult.Result;

public class NotNullValidator implements IValidator {

	private List<ValidationImpl> validations = new ArrayList<ValidationImpl>();
		
	private static final String ERROR_MSG_FORMAT = "The {0} cannot be null in {1}.";
	private static final String ERROR_MSG_FORMAT_BLANK = "The {0} cannot be blank in {1}.";

	@Override
	public IValidationResult validate(Object businessObject) throws Exception {
		ValidationResultImp resultImp = new ValidationResultImp();

		Class<? extends Object> clazz = businessObject.getClass();
		for (ValidationImpl validation : this.getValidations()) {
			Method method = clazz.getMethod(validation.getGetterMethod());
			boolean checkStringNotBlank = validation.isCheckStringNotBlank();
			
			Object result = method.invoke(businessObject);
			if (null == result) {
				resultImp.setResult(Result.FAILURE);
				String errorMsg = MessageFormat.format(ERROR_MSG_FORMAT, validation
						.getFormatObjects().toArray());
				resultImp.addErrorMsg(errorMsg);
			} else if(result instanceof String && checkStringNotBlank && !StringUtils.hasText(result.toString())){
				resultImp.setResult(Result.FAILURE);
				String errorMsg = MessageFormat.format(ERROR_MSG_FORMAT_BLANK, validation
						.getFormatObjects().toArray());
				resultImp.addErrorMsg(errorMsg);
			}
		}
		return resultImp;
	}

	public void setValidations(List<ValidationImpl> validations) {
		this.validations = validations;
	}

	public List<ValidationImpl> getValidations() {
		return validations;
	}
}
